import { FC, useEffect, useMemo, useRef, useState } from 'react';
import { RouteComponentProps } from 'react-router';
import { Row, Button, Tabs } from 'antd';
import _ from 'lodash';
import { useParams } from 'react-router-dom';
import { WithNormalRender } from "@ey-render/hoc-form";
import api, { archivesDetailJson, arcvList } from './services';
import { Form } from '@formily/core/esm/models';
import { onFieldValueChange, onFormMount } from '@formily/core';
import FileBoxDetail from '../file-box/detail';
import PzDetail from './detailpz';
import GeneralDetail from '@/pages/invoice/generalDetail';
import components from "@/components/schema-form-render/schema-components-registed/components-biz";

interface ArchivesMngDetailProps extends RouteComponentProps {}

const ArchivesMngDetail: FC<ArchivesMngDetailProps> = ({
    match,
    ...extra
}) => {
  const { code, type, boxCode } = useParams();

  const [needBtn, setNeedBtn] = useState(false);
  const [detailProps, setDetailProps] = useState<any>(null);
  const formRef = useRef<Form>();
  useEffect(() => {
    const footerLeftEl = document.querySelector('.content-footer');

    footerLeftEl.style.display = 'none';

    return () => {
      footerLeftEl.style.display = '';
    }
  }, [])

  useEffect(() => {
    if (!['Form','Vouchers'].includes(type)) return;
    archivesDetailJson({
      code,
      pageCode: 'ArcvManage_D'
    }).then((res: any) => {
      const {
        code,
        bizCode,
        refBizPageCode,
        refType,
        refCode,
        type,
        // attachmentCode,
        // invoiceType
      }: any = res.result || {};

      switch(type) {
        case 'Form':
          const bizPageCode = refBizPageCode?.split('_')[0] + '_D';
          setDetailProps({
            businessNo: refCode,
            businessType: bizPageCode,
            componentName: bizPageCode,
            pageType: refType,
            type
          });
          break;
        case 'Vouchers':
          setDetailProps({
            businessNo: refCode,
            businessType: refBizPageCode,
            componentName: refBizPageCode,
            pageType: refType,
            type
          });
          break;

        default:
          break;
      }
    })
  }, [code, type])


  const detailApi: any = useMemo(() => {
    return {
        remoteUrl: api.detail,
        method: 'POST',
        remoteParams: {
          code,
        },
        pageCode: 'ArcvManage_D',
    };
  }, [code]);

  const getArcvList = (bizCode: string) => {
    arcvList({
      bizCode,
      pageCode: "ArcvManage_L"
    }).then((res: any) => {
      if (res.success) {
        const relevanceArcv = res.result;

        formRef.current?.setValuesIn('relevanceArcv', relevanceArcv);
      }
    })
  }

  const BillFormLayout = useMemo(() => {
    return WithNormalRender({
      filedConfig: {},
      components: {
        ...components,
      },
    });
  }, []);

  const formRender = () => {
    switch(type) {
      case 'Form':
        return (
          <GeneralDetail pageType={detailProps.pageType} businessNo={ detailProps.businessNo } businessType={ detailProps.businessType } />
        );
      case  'Vouchers':
        return (
          <PzDetail
            btn={1}
            {...detailProps}
          />
        )
      default:
        return null;
    }
  }

  return (
    <>
      <Tabs defaultActiveKey="1">
        <Tabs.TabPane tab="案件详情" key="1">
          <BillFormLayout
            anchor
            type="DETAIL"
            {...detailApi}
            formConfigs={{
              effects: () => {
                onFormMount((form) => {
                  formRef.current = form;

                  setNeedBtn(!form.values.brwCode);

                  const { bizCode } = form.values;

                  getArcvList(bizCode)
                })
                onFieldValueChange('operationAuth', (field, form) => {
                  form.setFieldState('attachments', state => {
                    state.componentProps = {
                      ...state.componentProps,
                      operationAuth: field.value
                    }
                  })
                })
              }
            }}
            filedConfig={{}}
            eventMap={{
              previewInvoice: (e: any, index: string, rows: any) => {
                const target = rows?.[index]

                target && window.open(`/#/arcv/archives/archives-manage/detail/${target.code}/${target.type}/${target.boxCode || undefined}`)
              }
            }}
          />
        </Tabs.TabPane>
        {
          boxCode !== 'undefined' ?
            <Tabs.TabPane tab="档案盒详情" key="2">
              <FileBoxDetail
                {...extra}
              />
            </Tabs.TabPane> : null
        }
        {
          ['Form'].includes(type) && detailProps  && detailProps.businessNo  ?
            <Tabs.TabPane tab="单据详情" key="3">
              {formRender()}
            </Tabs.TabPane> : null
        }

{
          ['Vouchers'].includes(type) && detailProps ?
            <Tabs.TabPane tab="凭证详情" key="4">
              {formRender()}
            </Tabs.TabPane> : null
        }
      </Tabs>
    </>
  );
};

export default ArchivesMngDetail;
